package com.mobilesales.android.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

public class Geolocalization {
	private static String m_provider;

	public static Location getCurrentLocation(Context context) {
		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);

		boolean isGPSEnabled = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);

		// getting network status
		boolean isNetworkEnabled = locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		if (isNetworkEnabled) {
			locationManager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			m_provider = LocationManager.NETWORK_PROVIDER;
			Log.d("Network", "Network");
		}
		// if GPS Enabled get lat/long using GPS Services
		if (isGPSEnabled) {
			if (locationManager != null) {
				locationManager
						.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				m_provider = LocationManager.GPS_PROVIDER;
			}
		} else
			showErrorGPS(context);

		/*
		 * Criteria criteria = new Criteria(); String bestprovider =
		 * locationManager.getBestProvider(criteria, false);
		 * 
		 * Location location =
		 * locationManager.getLastKnownLocation(bestprovider);
		 */
		Location location = locationManager.getLastKnownLocation(m_provider);

		if (location == null) {
			List<String> providers = locationManager.getAllProviders();
			for (String p : providers) {
				location = locationManager.getLastKnownLocation(p);
				if (location != null)
					return location;
			}
		}
		Log.i("Geolocalization.getCurrentLocation",
				(location != null) ? location.toString() : "not found");
		return location;
	}

	private static void showErrorGPS(final Context context) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

		// Setting Dialog Title
		alertDialog.setTitle("GPS is settings");

		// Setting Dialog Message
		alertDialog
				.setMessage("GPS is not enabled. Do you want to go to settings menu?");

		// Setting Icon to Dialog
		// alertDialog.setIcon(R.drawable.delete);
		// On pressing Settings button
		alertDialog.setPositiveButton("Settings",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(
								android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						((Activity) context).startActivity(intent);
					}
				});

		// on pressing cancel button
		alertDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		// Showing Alert Message
		alertDialog.show();
	}

	public static Location reverseGeocode(Context context, String address) {
		if (address == null || address == "") {
			return null;
		}

		int maxResults = 1;

		Geocoder gc = new Geocoder(context, Locale.getDefault());
		List<Address> addresses = new ArrayList<Address>();
		try {
			addresses = gc.getFromLocationName(address, maxResults);
		} catch (IOException e) {
			Log.d("Geolocalization.reverseGeocode", e.getMessage());
			return null;
		}

		if (addresses.size() == 1) {
			Location loc = new Location("Geolocalization");
			loc.setLatitude(addresses.get(0).getLatitude());
			loc.setLongitude(addresses.get(0).getLongitude());
			return loc;
		} else {
			return null;
		}
	}

	public static String geocode(Context context, Location location) {
		if (location == null) {
			return null;
		}
		double latitude = location.getLatitude();
		double longitude = location.getLongitude();
		int maxResults = 1;

		Geocoder gc = new Geocoder(context, Locale.getDefault());
		List<Address> addresses = new ArrayList<Address>();
		try {
			addresses = gc.getFromLocation(latitude, longitude, maxResults);
		} catch (IOException e) {
			Log.d("Geolocalization.geocode", e.getMessage());
			return null;
		}

		if (addresses.size() == 1) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
				sb.append(addresses.get(0).getAddressLine(i)).append("\n");
			return sb.toString();
		} else {
			return null;
		}
	}
}
